<template>
  <div id="volpic" class="app-container">
    <el-dialog
      title="新增广告图片"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form id="volpic" ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="50px">
        <el-form-item label="栏目" prop="classId">
          <el-select v-model="postForm.classId" placeholder="请选择栏目">
            <el-option-group
              v-for="group in infoClassList"
              :key="group.id"
              :label="group.classname"
            >
              <el-option
                v-for="item1 in group.children"
                :key="item1.id"
                :label="item1.classname"
                :value="item1.id"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="pics">
          <div
            v-for="item2 in postForm.pics"
            :key="item2.id"
            style="float:left"
          >
            <el-image
              style="width: 100px; height: 100px;margin-right:10px;"
              :src="$http.defaults.baseURL + 'api/mpfile/download?id=' + item2.id"
              fit="fill"
              :preview-src-list="postForm.pics.map(item => $http.defaults.baseURL + 'api/mpfile/download?id=' + item2.id)"
            />
            <div>
              <el-popconfirm
                title="此操作无需保存，立即删除该图片信息，确定删除吗？"
                @onConfirm="delPic(item2.id)"
              >
                <el-button slot="reference" type="text" style="text-align:center;margin:0 0 0 33px;">删除</el-button>
              </el-popconfirm>
            </div>
          </div>
          <el-upload
            style="float:left"
            class="avatar-uploader"
            :action="this.$http.defaults.baseURL+'api/mpfile/upload/'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="myHeaders"
            accept="image/jpeg,image/png,image/gif"
            multiple
          >
            <i class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="success" :loading="loading" @click="submitPic">
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <div class="filter-container">
      <div style="float:left;margin-bottom:10px">{{ volname }}
        <el-select v-model="listQuery.classId" placeholder="请选择栏目" style="margin-left:10px;" clearable>
          <el-option-group
            v-for="group in infoClassList"
            :key="group.id"
            :label="group.classname"
          >
            <el-option
              v-for="item1 in group.children"
              :key="item1.id"
              :label="item1.classname"
              :value="item1.id"
            />
          </el-option-group>
        </el-select>
        <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin:0 10px;" @click="handleFilter">
          搜索
        </el-button>
      </div>
      <el-button class="filter-item" type="success" icon="el-icon-plus" style="margin:0;float:right" @click="handleAdd">
        新增
      </el-button>
    </div>
    <template>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @sort-change="sortChange"
      >
        <!-- <el-table-column v-if="roleEdit" type="selection" width="50" align="center" /> -->

        <el-table-column
          align="center"
          type="index"
          label="序号"
          width="50px"
        />

        <el-table-column min-width="200px" prop="companyName" label="图片">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 50px"
              :src="$http.defaults.baseURL+'api/mpfile/download?id='+scope.row.id"
              :preview-src-list="[$http.defaults.baseURL+'api/mpfile/download?id='+scope.row.id]"
              fit="contain"
            />
          </template>
        </el-table-column>
        <el-table-column width="300px" prop="businessId" align="center" label="栏目">
          <template slot-scope="scope">
            {{ infoClassName(scope.row.businessId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-popconfirm title="确定删除该信息吗？" style="margin-left:10px;" @onConfirm="deleteData(scope.row.id)">
              <el-button slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </div>
</template>

<script>
// import { fetchList } from '@/api/article'

export default {
  name: 'ArticleList',
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        // this.$message({
        //   message: '请将表单填写完整',
        //   type: 'error'
        // })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      myHeaders: {},
      postForm: { classId: null, pics: [] },
      infoClassList: [],
      volname: null,
      item: {},
      dialogtitle: '',
      dialogVisible: false,
      allDialogVisible: false,
      readOnly: false,
      timestamp: '',
      list: [
      ],
      total: 0,
      listLoading: true,
      listQuery: {
        classId: ''
      },
      Sortkey: '',
      Isace: '',
      multipleSelection: [],
      id: '',
      rules: {
        classId: [{ validator: validateRequire }]
      }
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    this.getInfoClass()
    this.getList()
    this.showVolName()
  },
  created() {
    this.getList()
  },
  methods: {
    infoClassName(id) {
      let classname = ''
      this.infoClassList.forEach(item => {
        item.children.forEach(it => {
          if (it.id === id) {
            classname = item.classname + ' > ' + it.classname
          }
        })
      })
      return classname
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.postForm.pics.push(res.result[0])
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    delPic(id) {
      this.$http
        .get('/api/genFileInfo/remove?id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            // this.getDetail(this.$route.query.id)
            this.postForm.pics = this.postForm.pics.filter(item => item.id !== id)
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    submitPic() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          const para = {
            classId: this.postForm.classId,
            fileIds: this.postForm.pics.map(item => item.id),
            volId: this.$route.query.id
          }
          this.loading = true
          this.$http
            .post('/api/busInfo/updateClassVolFile', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.getList()
                this.dialogVisible = false
                this.postForm = { classId: null, pics: [] }
              } else {
                console.log('操作失败:' + response.data.message)
                this.$message({
                  message: '操作失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleAdd() {
      this.dialogVisible = true
    },
    getInfoClass() {
      this.$http
        .get('/api/busInfoClass/getLevelList')
        .then(response => {
          if (response.data.success === true) {
            this.infoClassList = response.data.result
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    showVolName() {
      this.$http
        .get('/api/busVol/getById?id=' + this.$route.query.id)
        .then(response => {
          if (response.data.success === true) {
            const year = new Date(response.data.result.pubdate).getFullYear()
            const nowyear = new Date().getFullYear()
            let volname = parseInt(response.data.result.name)
            if (year !== nowyear) {
              volname = (year - 2000) * 1000 + volname
            }
            this.volname = volname + '期'
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    fAuthStatus(id) {
      if (id) {
        return this.statusList.find(item => item.id === id).label
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteData(id) {
      this.$http
        .get('/api/mpfile/remove?id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getList()
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    sortChange(column, prop, order) {
      this.Sortkey = column.prop
      if (column.order === 'ascending') {
        this.Isace = 'asc'
      } else {
        this.Isace = 'desc'
      }
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    detail(id, type) {
      this.id = id
      this.dialogtitle = '查看'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    dialogHide(flag) {
      this.dialogVisible = false
      this.getList()
    },
    getList() {
      this.listLoading = true
      this.$http
        .get('/api/busInfo/getClassVolFiles?volId=' + this.$route.query.id + '&classId=' + this.listQuery.classId)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            this.list = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.listLoading = false
        })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
<style >
  #volpic .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  #volpic .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  #volpic .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
</style>
